import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../data/models/user.dart';
import '../../../utils/storage_service.dart';
import '../../../config/app_constants.dart';

class ProfileController extends GetxController {
  late StorageService _storageService;

  // 用户信息
  final Rx<User> currentUser = User.empty().obs;
  
  // 登录状态
  final RxBool isLoggedIn = false.obs;
  
  // 加载状态
  final RxBool isLoading = false.obs;

  @override
  void onInit() {
    super.onInit();
    _initializeStorage();
    _loadUserData();
  }

  // 初始化存储服务
  Future<void> _initializeStorage() async {
    _storageService = await StorageService.getInstance();
  }

  // 加载用户数据
  Future<void> _loadUserData() async {
    try {
      await _initializeStorage();
      
      final userData = _storageService.getUserData();
      if (userData != null) {
        currentUser.value = User.fromJson(userData);
        isLoggedIn.value = currentUser.value.isLoggedIn;
      }
    } catch (e) {
      print('Error loading user data: $e');
    }
  }

  // 登录
  Future<void> login(String username, String password) async {
    try {
      isLoading.value = true;
      
      // 模拟登录过程
      await Future.delayed(const Duration(seconds: 2));
      
      // 这里应该调用实际的登录API
      // 现在使用模拟数据
      if (username.isNotEmpty && password.isNotEmpty) {
        final user = User(
          id: 'user_${DateTime.now().millisecondsSinceEpoch}',
          username: username,
          email: '$username@example.com',
          avatarUrl: 'https://via.placeholder.com/150',
          isLoggedIn: true,
          lastLoginTime: DateTime.now(),
        );
        
        currentUser.value = user;
        isLoggedIn.value = true;
        
        // 保存用户数据
        await _storageService.setUserData(user.toJson());
        
        Get.snackbar(
          '登录成功',
          AppConstants.successLoginMessage,
          snackPosition: SnackPosition.BOTTOM,
          duration: const Duration(seconds: 2),
        );
      } else {
        throw Exception('用户名和密码不能为空');
      }
    } catch (e) {
      Get.snackbar(
        '登录失败',
        e.toString(),
        snackPosition: SnackPosition.BOTTOM,
        duration: const Duration(seconds: 3),
      );
    } finally {
      isLoading.value = false;
    }
  }

  // 退出登录
  Future<void> logout() async {
    try {
      isLoading.value = true;
      
      // 清除用户数据
      await _storageService.remove(AppConstants.keyUserData);
      
      currentUser.value = User.empty();
      isLoggedIn.value = false;
      
      Get.snackbar(
        '退出成功',
        AppConstants.successLogoutMessage,
        snackPosition: SnackPosition.BOTTOM,
        duration: const Duration(seconds: 2),
      );
    } catch (e) {
      Get.snackbar(
        '退出失败',
        '退出登录时发生错误: $e',
        snackPosition: SnackPosition.BOTTOM,
        duration: const Duration(seconds: 3),
      );
    } finally {
      isLoading.value = false;
    }
  }

  // 显示登录对话框
  void showLoginDialog() {
    Get.dialog(
      _buildLoginDialog(),
      barrierDismissible: true,
    );
  }

  // 构建登录对话框
  Widget _buildLoginDialog() {
    final usernameController = TextEditingController();
    final passwordController = TextEditingController();
    
    return Obx(
      () => AlertDialog(
        title: const Text('登录'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: usernameController,
              decoration: const InputDecoration(
                labelText: '用户名',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            TextField(
              controller: passwordController,
              decoration: const InputDecoration(
                labelText: '密码',
                border: OutlineInputBorder(),
              ),
              obscureText: true,
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: isLoading.value
                ? null
                : () async {
                    await login(
                      usernameController.text,
                      passwordController.text,
                    );
                    if (isLoggedIn.value) {
                      Get.back();
                    }
                  },
            child: isLoading.value
                ? const SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(strokeWidth: 2),
                  )
                : const Text('登录'),
          ),
        ],
      ),
    );
  }

  // 显示关于对话框
  void showAboutDialog() {
    Get.dialog(
      AlertDialog(
        title: const Text('关于'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('应用名称: ${AppConstants.appName}'),
            const SizedBox(height: 8),
            Text('版本: ${AppConstants.appVersion}'),
            const SizedBox(height: 8),
            Text('描述: ${AppConstants.appDescription}'),
            const SizedBox(height: 16),
            const Text(
              '这是一个基于Flutter开发的游戏Wiki应用，'
              '使用GetX框架实现MVVM架构，支持多个游戏Wiki的浏览和搜索。',
              style: TextStyle(fontSize: 14),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  // 更新用户头像
  Future<void> updateAvatar(String avatarUrl) async {
    try {
      if (isLoggedIn.value) {
        final updatedUser = currentUser.value.copyWith(avatarUrl: avatarUrl);
        currentUser.value = updatedUser;
        await _storageService.setUserData(updatedUser.toJson());
        
        Get.snackbar(
          '更新成功',
          '头像已更新',
          snackPosition: SnackPosition.BOTTOM,
          duration: const Duration(seconds: 2),
        );
      }
    } catch (e) {
      Get.snackbar(
        '更新失败',
        '头像更新失败: $e',
        snackPosition: SnackPosition.BOTTOM,
        duration: const Duration(seconds: 3),
      );
    }
  }

  // 获取用户显示名称
  String get displayName {
    if (isLoggedIn.value && currentUser.value.username.isNotEmpty) {
      return currentUser.value.username;
    }
    return '未登录';
  }

  // 获取用户头像URL
  String get avatarUrl {
    if (isLoggedIn.value && currentUser.value.avatarUrl.isNotEmpty) {
      return currentUser.value.avatarUrl;
    }
    return 'https://via.placeholder.com/150'; // 默认头像
  }
}

